﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI.WebControls;
using Meqs.Entity;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;
using Meqs.Entity.Views;

public partial class Credit_Teacher_Reprots_CreditOfGraduation : ContainerBasePage
{
    private CauseFormula causeFormula;
    private CauseLevelTool causeLevelTool;
    
    private int schoolYear;
    private int term;
    private int clsId;

    IGlobalCauseInfoLogic causeLogic = Container<IGlobalCauseInfoLogic>.Instance;
    IList<GlobalCauseInfo> _allCauseList;

    protected void Page_Load(object sender, EventArgs e)
    {
        // 获取学校性质
        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", SchoolMark);
        IList<SchoolInfo> schoolList = Container<ISchoolInfoLogic>.Instance.FindAll(ht);
        if (schoolList == null || schoolList.Count < 1)
            return;

        _allCauseList = causeLogic.SelectSchoolCause(SchoolMark, 1);

        causeFormula = new CauseFormula(SchoolMark, 0);
        causeLevelTool = new CauseLevelTool(SchoolCommon.Sch_SchoolInfo.SchoolYear, SchoolCommon.Sch_SchoolInfo.SchoolTerm, SchoolMark);

        BindSchoolYear();
        if (!IsPostBack)
        {
            selYear_TextChanged(selYear, new EventArgs());
            selClass_TextChanged(selClass, new EventArgs());
        }
    }
    /// <summary>
    /// 绑定班级下拉框
    /// </summary>
    protected void BindClass(int schoolYear, int term)
    {
        selClass.Items.Clear();
        IList<ClsInfo> schoolList = Container<IClassHistoryLogic>.Instance.FindClassesInSchoolYear(schoolYear, SchoolMark, null);
        ListSort<ClsInfo> sortList = new ListSort<ClsInfo>(schoolList, "Grade");
        schoolList = sortList.Sort();
        if (schoolList == null || schoolList.Count < 1)
            return;

        foreach (ClsInfo info in schoolList)
        {
            String str = "";
            switch (info.Grade)
            {
                case 1:
                    str = "一年级";
                    break;
                case 2:
                    str = "二年级";
                    break;
                case 3:
                    str = "三年级";
                    break;
                case 4:
                    str = "四年级";
                    break;
                case 5:
                    str = "五年级";
                    break;
                case 6:
                    str = "六年级";
                    break;
                case 7:
                    str = "初一";
                    break;
                case 8:
                    str = "初二";
                    break;
                case 9:
                    str = "初三";
                    break;
                case 10:
                    str = "高一";
                    break;
                case 11:
                    str = "高二";
                    break;
                case 12:
                    str = "高三";
                    break;
            }

            #region 班级过滤
            List<int> enableClassList = SchoolCommon.CanViewClasses((int)SecurityTable.Security.Credit_CanView, schoolYear, term);
            bool enableClass = false;
            if (enableClassList != null)
            {
                foreach (int i in enableClassList)
                {
                    if (info.RID != i ) continue;
                    enableClass = true;
                    break;
                }
                if (!enableClass)
                    continue;
            }
            #endregion

            selClass.Items.Add(new ListItem(String.Format("{0}({1})班", str, info.ClsNo), info.RID.ToString()));
        }
        selClass_TextChanged(selClass, new EventArgs());
    }

    /// <summary>
    /// 绑定学期下拉框
    /// </summary>
    protected void BindSchoolYear()
    {
        //Hashtable ht = new Hashtable();
        //ht.Add("SchoolMark", SchoolMark);
        //IList<StuCauseEvalHistory> historyList = Container<IStuCauseEvalHistoryLogic>.Instance.FindAll(ht);
        //if (historyList == null || historyList.Count < 1)
        //{
        //    selYear.Items.Add(new ListItem("没有历史数据", "-1"));
        //}
        //IList<String> strList = new List<String>();
        //if (historyList != null)
        //    foreach (StuCauseEvalHistory history in historyList)
        //    {
        //        String value = String.Format("{0},{1}", history.SchoolYear, history.Term);
        //        if (!strList.Contains(value))
        //        {
        //            int year = 0;
        //            int term = 0;
        //            if (!Int32.TryParse(history.SchoolYear.ToString(), out year))
        //                return;
        //            if (!Int32.TryParse(history.Term.ToString(), out term))
        //                return;
        //            String str = Common.ConvertYearAndTerm(year, term);
        //            selYear.Items.Add(new ListItem(str, value));
        //            strList.Add(value);
        //        }
        //    }
        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", si.SchoolMark);
        IList<TermInfo> terms = Container<ITermInfoLogic>.Instance.FindAll(ht);
        foreach (TermInfo term in terms)
        {
            String str = Common.ConvertYearAndTerm(term.SchoolYear, term.Term);
            String value = String.Format("{0},{1}", term.SchoolYear, term.Term);
            selYear.Items.Add(new ListItem(str, value));
        }
    }

    /// <summary>
    /// 学期下拉框事件
    /// </summary>
    protected void selYear_TextChanged(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            return;

        BindClass(nYear, nTerm);
    }

    /// <summary>
    /// 学期下拉框事件
    /// </summary>
    protected void selClass_TextChanged(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;
        int nClass = 0;

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            return;

        if (!Int32.TryParse(selClass.SelectedValue, out nClass))
            return;

        Hashtable ht = new Hashtable();
        ht.Add("RID", nClass);
        ht.Add("SchoolMark", SchoolMark);
        IList<ClsInfo> cilist = Container<IClsInfoLogic>.Instance.FindAll(ht);
    }


    protected void btnBind_Click(object sender, EventArgs e)
    {
        //string s = txtSchoolYear.Text;
        //if (!string.IsNullOrEmpty(s))
        //    int.TryParse(s, out schoolYear);

        //s = txtTerm.Text;
        //if (!string.IsNullOrEmpty(s))
        //    int.TryParse(s, out term);

        //s = txtClsId.Text;
        //if (!string.IsNullOrEmpty(s))
        //    int.TryParse(s, out clsId);

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out schoolYear))
            return;

        if (!Int32.TryParse(outString[1], out term))
            return;

        if (!Int32.TryParse(selClass.SelectedValue, out clsId))
            return;


        Bind();
    }

    private void Bind()
    {
        List<CauseInfo> list = new List<CauseInfo>();
        CauseInfo item = new CauseInfo();
        item.RID = 1;
        item.SchoolMark = SchoolMark;
        list.Add(item);
        repeater1.DataSource = list;
        repeater1.DataBind();
    }

    protected string InitTableHead()
    {

        int width = 490;
        int index = 2;
        StringBuilder sb1 = new StringBuilder("<tr><th class='FixedRowCol' rowspan='2' style='width:50px;'>序号</th><th class='FixedRowCol' rowspan='2' style='width:100px;'>学号</th><th class='FixedRowCol' rowspan='2' style='width:100px;'>姓名</th>");
        StringBuilder sb2 = new StringBuilder("<tr>");
        foreach (GlobalCauseInfo item in _allCauseList)
        {
            width += 120;
            sb1.Append(String.Format("<th class='FixedRow' colspan='2'>{0}</th>", item.CauseName));
            sb2.Append(String.Format("<th class='FixedRow' style='width:60px;' onclick='sort({0})'>学分<span id='img{0}' title='学分'></span></th><th class='FixedRow' style='width:60px;'>评价等级</th>", index + 1));
            index += 2;
        }
        width += 120;
        sb1.Append("<th class='FixedRow' colspan='2'>德育</th>");
        sb2.Append(String.Format("<th class='FixedRow' style='width:60px;' onclick='sort({0})'>学分<span id='img{0}' title='学分'></span></th><th class='FixedRow' style='width:60px;'>评价等级</th>", index + 1));
        index += 2;
        sb1.Append(String.Format("<th class='FixedRow' rowspan='2' style='width:80px;' onclick='sort({0})'>毕业综合评价<span id='img{0}' title='毕业综合评价'><img src='../../Common/images/1.gif' /></span></th>", index + 1));
        sb1.Append("<th class='FixedRow' rowspan='2' style='width:80px;'>毕业综合评价等级</th></tr>");
        sb2.Append("</tr>");
        string strTable = String.Format("<table id='settingTable' border='0' cellpadding='0' cellspacing='1' class='useList1' style='width:{0}px;'>", width);

        Hashtable ht = new Hashtable();
        ht.Add("RID", clsId);
        ht.Add("SchoolMark", SchoolMark);
        IList<ClsInfo> cilist = Container<IClsInfoLogic>.Instance.FindAll(ht);
        string strTitle = String.Format("<tr><th class='FixedRowCol' colspan='" + (_allCauseList.Count * 2 + 5) + "' style='text-align:left;'>" + cilist[0].ClsName + "毕业综合评价</th></tr>");
        return strTable + strTitle + sb1 + sb2;
    }


    protected string InitTableBody()
    {
        Hashtable ht = new Hashtable();
        ht.Add("ClassID", clsId);
        ht.Add("SchoolYear", schoolYear);
        ht.Add("Term", term);
        IList<StudentInfo> sinfo = Container<IStudentHistoryLogic>.Instance.FindHistoryStudents(schoolYear,
            term, clsId, SchoolMark);

        // _allCauseList 
        // 获取分数数据
        IList<GraduationScore> gList = Container<IStuCausePersonCatchLogic>.Instance.GetGraduationScore(SchoolMark, clsId);
        StringBuilder sb = new StringBuilder();

        int index = 1;
        int lastStuID = 0;
        // <stuid, <courseid, <"count", "score">>
        Dictionary<int, Dictionary<int, Dictionary<string, double>>> dicScore = new Dictionary<int, Dictionary<int, Dictionary<string, double>>>();
        Dictionary<int, Dictionary<int, Dictionary<string, double>>> dicMScore = new Dictionary<int, Dictionary<int, Dictionary<string, double>>>();

        foreach(GraduationScore gi in gList)
        {
            gi.Score = causeFormula.GetCauseScore(gi.Score, gi.Testscore, gi.CourseID);
            gi.Mscore = causeFormula.GetMoralScore(gi.Mscore);

            if (dicScore.ContainsKey(gi.Rid))
            {
                if (dicScore[gi.Rid].ContainsKey(gi.CourseID))
                {
                    dicScore[gi.Rid][gi.CourseID]["count"] += 1;
                    dicScore[gi.Rid][gi.CourseID]["score"] += gi.Score;
                }
                else
                {
                    Dictionary<string, double> dtemp = new Dictionary<string, double>();
                    dtemp.Add("count", 1);
                    dtemp.Add("score", gi.Score);
                    dicScore[gi.Rid].Add(gi.CourseID, dtemp);
                }
            }
            else 
            {
                Dictionary<int, Dictionary<string, double>> dictt = new Dictionary<int, Dictionary<string, double>>();
                Dictionary<string, double> dtemp = new Dictionary<string, double>();
                dtemp.Add("count", 1);
                dtemp.Add("score", gi.Score);
                dictt.Add(gi.CourseID, dtemp);
                dicScore.Add(gi.Rid, dictt);
            }
            if (gi.Mscore != 0)
            {
                if (dicMScore.ContainsKey(gi.Rid))
                {
                    if (dicMScore[gi.Rid].ContainsKey(0))
                    {
                        dicMScore[gi.Rid][0]["count"] += 1;
                        dicMScore[gi.Rid][0]["score"] += gi.Mscore;
                    }
                    else
                    {
                        Dictionary<string, double> dtemp = new Dictionary<string, double>();
                        dtemp.Add("count", 1);
                        dtemp.Add("score", gi.Mscore);
                        dicMScore[gi.Rid].Add(0, dtemp);
                    }
                }
                else
                {
                    Dictionary<int, Dictionary<string, double>> dictt = new Dictionary<int, Dictionary<string, double>>();
                    Dictionary<string, double> dtemp = new Dictionary<string, double>();
                    dtemp.Add("count", 1);
                    dtemp.Add("score", gi.Mscore);
                    dictt.Add(0, dtemp);
                    dicMScore.Add(gi.Rid, dictt);
                }
            }
        }

        foreach (GraduationScore gi in gList)
        {
            if (gi.Rid == lastStuID) continue;

            lastStuID = gi.Rid;
            sb.Append(String.Format("<tr><td class='FixedCol'>{0}</td><td class='FixedCol'>{1}</td><td class='FixedCol'>{2}</td>", index, gi.StuCode, gi.StuName));
            index++;
            double allsum = 0;
            int courseCount = _allCauseList.Count;
            // 各科
            foreach (GlobalCauseInfo gci in _allCauseList)
            {
                if(!dicScore.ContainsKey(gi.Rid))
                    continue;
                if(!dicScore[gi.Rid].ContainsKey(gci.RID))
                {
                    sb.Append("<td>-</td><td>-</td>");
                    courseCount--;
                    continue;
                }
                double sc = dicScore[gi.Rid][gci.RID]["score"]/dicScore[gi.Rid][gci.RID]["count"];
                sc = Math.Round(sc > 100 ? 100 : sc, 2);
                string level = causeLevelTool.GetCauseLevel(schoolYear, term, sc);
                sb.Append(String.Format("<td>{0}</td><td>{1}</td>", sc, level));
                allsum += sc;
            }
            // 德育
            //double mscore = (dicMScore[gi.Rid][0]["count"] == 0) ? 0: dicMScore[gi.Rid][0]["score"] / dicMScore[gi.Rid][0]["count"];
            double mscore = (dicMScore.Count == 0 || dicMScore.ContainsKey(gi.Rid)==false || dicMScore[gi.Rid][0]["count"] == 0) ? 0 : dicMScore[gi.Rid][0]["score"] / dicMScore[gi.Rid][0]["count"];
            mscore = Math.Round(mscore > 100 ? 100 : mscore,2);
            if (dicMScore[gi.Rid][0]["count"] != 0)
            {
                courseCount++;
            }
            allsum += mscore;
            sb.Append(String.Format("<td>{0}</td><td>{1}</td>", 
                 mscore, 
                causeLevelTool.GetCauseLevel(schoolYear, term,  mscore)));

            // 总分
            double allscore = Math.Round(allsum / courseCount, 2);
            allscore = allscore > 100 ? 100 : allscore;
            sb.Append(String.Format("<td>{0}</td><td>{1}</td>",
                allscore,
                causeLevelTool.GetCauseLevel(schoolYear, term, allscore)));
            sb.Append("</tr>");
        }
        sb.Append("</tr>");

        return sb.ToString();
    }

    [WebMethod]
    public static string GetExcel(string clsName, ExcelTableCell[][] cells)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "download\\" + DateTime.Now.Ticks.ToString() + "_profile.xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, clsName + "毕业学分表", 3, 0, cells);
        return "";
    }
}
